<?php
declare (strict_types=1);

namespace app\api\service\Activity;

use app\api\model\UserOauth as UserOauthModel;
use app\common\service\bangdou\Common;
use app\common\service\BaseService;
use app\common\library\helper;
use cores\exception\BaseException;

/**
 * 订单优惠券折扣服务类
 * Class RegActivity
 * @package app\api\service\Activity\RegActivity
 */
class RegActivity extends BaseService
{
    /**
     * 给新注册用户发现金券
     * @param $user_id 用户id
     * @param $activity_type 7邦豆 6现金券 5礼金券
     * @param $activity_value 赠送的值
     * @param $remarks 备注
     * @return mixed
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function sendByUserIdCoupon($user_id,$activity_type,$activity_value,$remarks){
        if(empty($user_id)){
            throwError('用户不存在');
        }
        $user = UserOauthModel::getOauth($user_id, getPlatform());

        if(!isset($user['bd_uid']) || empty($user['bd_uid'])){
            throwError('用户bd_uid不存在');
        }else{
            $bd_uid = $user['bd_uid'];
        }
        $token_array = Common::createToken($bd_uid);
        $type = [7,6,5];
        if(!in_array($activity_type,$type)){
            throwError('赠送类型不存在');
        }

        $params['userId'] = $user['bd_uid'];
        $params['cashCouponAmount'] = $activity_value;
        $params['organ_id'] = Common::ORGANID;;
        $params['store_id'] = $user['store_id'];;
        $params['remark'] = $remarks;

        $params['timestamp'] = time();
        $sign = Common::getBangDouApiSign($params);
        $params['sign'] = $sign;
        $url = app()->config->get('app.bd_api_url').'/CashCoupon/Manage/sendByUserIdFromOtherPlatform';
        $headers = [
            'Content-Type: application/json',
            "Authorization: Bearer {$token_array['token']}"
        ];
        $result = helper::httpRequest($url, json_encode($params), $headers);
        log_record($result);
        return json_decode($result, true);
    }
}